package net.wicp.tams.common.redis.builder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang3.Validate;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import lombok.Builder;
import lombok.Builder.Default;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.redis.pool.JedisPoolTams;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Protocol;

@Builder
@Slf4j
@Getter
public class RedisStandaloneBuilderTams {
	private GenericObjectPoolConfig<Jedis> poolConfig;
	private static final Lock LOCK = new ReentrantLock();
	@Default
	private int timeout = Protocol.DEFAULT_TIMEOUT;// 创建池的最大时间
	@Default
	private final JedisPoolTams jedisPoolTams = new JedisPoolTams();
	@Default
	private String host = Conf.get("common.redis.redisserver.host");
	@Default
	private int port = Conf.getInt("common.redis.redisserver.port");

	private void init() {
		Validate.notNull(poolConfig, "需要配置信息");
		poolConfig.setJmxEnabled(true);
		poolConfig.setJmxNamePrefix("jedis-pool");
		if (!jedisPoolTams.isInit()) {
			while (true) {
				try {
					LOCK.tryLock(100, TimeUnit.MILLISECONDS);
					if (!jedisPoolTams.isInit()) {
						JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout,
								StringUtil.hasNull(Conf.get("common.redis.redisserver.password"), null),
								Conf.getInt("common.redis.redisserver.defaultDb"),
								Conf.get("common.redis.redisserver.clientName"));
						jedisPoolTams.setJedisPool(jedisPool);
						LOCK.unlock();
						break;
					}
				} catch (InterruptedException e) {
					log.error("error in build().", e);
				}
			}
		}
		log.info("---------------the pool inited---------------");
	}

	public static class InternalBuilder extends RedisStandaloneBuilderTamsBuilder {
		InternalBuilder() {
			super();
		}

		@Override
		public RedisStandaloneBuilderTams build() {
			RedisStandaloneBuilderTams model = super.build();
			model.init();
			return model;
		}
	}

	public static RedisStandaloneBuilderTamsBuilder builder() {
		return new InternalBuilder();
	}
}
